import React from 'react'
import dispatcher from 'lib/dispatcher'
import cx from 'classnames'
import moment from 'moment'
import DatePicker from 'lib/components/datepicker.jsx'
import _ from 'underscore'
import $ from 'jquery'

/**
 * 阻止事件冒泡
 *
 * @private
 * @param {Object} event event.
 * @return {Undefined}
 */
let stopPropagation = function(event) {
  event.stopPropagation();

  if ( event.nativeEvent ) {
    event.nativeEvent.stopImmediatePropagation();
  }
}

class DatePicker2 extends DatePicker {
  onForward(key){
    var next = moment(this.state.currentShow).add(1, 'month');
    if(!next.isAfter(this.props.maxDate)) {
      this.setState(this.stateFromDate(next.valueOf(), false), this._onChange);
    } else {
      this.setState(this.stateFromDate(this.props.maxDate.valueOf(), false), this._onChange);
    }
  }

  onBackward(key){
    var previous = moment(this.state.currentShow).subtract(1, 'month');
    if(!previous.isBefore(this.props.minDate)) {
      this.setState(this.stateFromDate(previous.valueOf(), false), this._onChange);
    } else {
      this.setState(this.stateFromDate(this.props.minDate, false), this._onChange)
    }
  }

  isDisabled(timestamp,month,currentMonth){
    return !(timestamp >= this.props.minDate && timestamp <= this.props.maxDate) || month !== undefined && month !== currentMonth
  }

  selectDay(date, event) {
    stopPropagation(event);

    this.setState(this.stateFromDate(date),this._onChange)
  }

  render() {
    return (
      <div className="calendar-date">
        <table className="table-condensed">
          <thead>
            <tr>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowBackward?this.onBackward:null}>
                  &#xe63e;
                </i>
              </th>
              <th colSpan="5">
                {this.state.year}年 {this.state.month+1}月
              </th>
              <th>
                <i className="iconfont arrow" style={{color:'#555'}} onClick={this.state.allowForward?this.onForward:null}>
                  &#xe63f;
                </i>
              </th>
            </tr>
            <tr>
              <th>日</th>
              <th>一</th>
              <th>二</th>
              <th>三</th>
              <th>四</th>
              <th>五</th>
              <th>六</th>
            </tr>
          </thead>
          <tbody>
            {
              this.state.matrix.map(function(week,n){
                return (
                  <tr key={n}>
                    {
                      week.map(function(dayObj){
                        if(this.isDisabled(dayObj.value,dayObj.month,this.state.month)){
                          return (
                            <td className="disabled" key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }else{
                          return (
                            <td onClick={this.selectDay.bind(this,dayObj.value)} className={cx({
                                active:dayObj.date === this.state.date && dayObj.month === this.state.month
                              })} key={dayObj.date}>
                              {dayObj.label}
                            </td>
                          )
                        }
                      },this)
                    }
                  </tr>
                )
              },this)
            }
          </tbody>
        </table>
      </div>
    )
  }
}

export default class DateComparerPicker extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      isOpen: false,
      displayText: props.displayText || '对比时段',
      isLastWeek: true,
      endTime: props.endTime ? moment(props.endTime).subtract(1, 'days').valueOf() : moment().startOf('day').valueOf()
    };

    this.toggle = this.toggle.bind(this);
    this.dayChanged = this.dayChanged.bind(this);
    this.applyHandler = this.applyHandler.bind(this);
    this.globalCloseDisplay = this.globalCloseDisplay.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      displayText: nextProps.displayText || '对比时段',
      endTime: nextProps.endTime ? moment(nextProps.endTime).subtract(1, 'days').valueOf() : moment().startOf('day').valueOf()
    });
  }

  toggle(event) {
    stopPropagation(event);
    this.setState({isOpen: !this.state.isOpen});
  }

  dayChanged(date) {
    this.setState({endTime: date});
  }

  selectDay(isLastWeek) {
    let unit = isLastWeek ? 'weeks' : 'months';
    this.setState({
      isLastWeek,
      endTime:moment().startOf('day').subtract(1, unit).valueOf()
    });
  }

  applyHandler() {
    var text = moment(this.state.endTime - this.props.spanTime).format('YYYY-MM-DD') + ' ~ ' + moment(this.state.endTime).format('YYYY-MM-DD');
    this.setState({displayText: text, isOpen: false}, () => {
      dispatcher.dispatch({
        $type: 'compare_date_range',
        id:this.props.id,
        data: {
          spanTime: this.props.spanTime,
          endTime: moment(this.state.endTime).add(1, 'days').valueOf(),
          displayText: this.state.displayText
        }
      });
    });
  }

  globalCloseDisplay(e) {
    if (this.state.isOpen) {
      if(!$.contains(this.refs.root, e.target)) {
        this.setState({isOpen: false});
      }
    }
  }

  componentDidMount() {
    this.__register = dispatcher.register((action) => {
      if (action.$type === 'reset_date_comparer') {
        this.setState({
          isOpen: false,
          displayText: '对比时段',
          endTime: moment().startOf('day').valueOf()
        });
      }
    });

    $(document).on('click', this.globalCloseDisplay);
  }

  componentWillUnmount() {
    dispatcher.unregister(this.__register);
    $(document).off('click', this.globalCloseDisplay);
  }

  renderBody() {
    let minDate = moment().startOf('day').subtract(3, 'months').valueOf();
    let maxDate = moment().startOf('day').valueOf();

    let endTime = moment(this.state.endTime).format('YYYY-MM-DD');
    let startTime = moment(this.state.endTime - this.props.spanTime).add(1, 'days').format('YYYY-MM-DD');

    return (
      <div ref="root" className="mi-timepicker-dropdown-main" style={{width: 286}}>
        <div className="timepicker-main" style={{width: 270,margin:'0 auto',paddingTop:'0px'}}>
          <div style={{'marginBottom': '10px'}}>
            <span style={{color:'#c2c2c2'}}>{startTime} - </span><span>{endTime}</span>
            <span className="float-right" style={{color:'#c2c2c2'}}>({moment.duration(this.props.spanTime).asDays()} 天)</span>
          </div>
          <div style={{'marginBottom': '10px'}}>
            选择对比时间段结束日期
          </div>
          <div className="timepicker-diy">
            <DatePicker2
              key={moment().valueOf()}
              minDate={minDate}
              maxDate={maxDate}
              defaultValue={this.state.endTime}
              onAfterChange={this.dayChanged} />
          </div>
        </div>
        <div className="timepicker-footer">
          <span style={{
            float: 'left',
            marginLeft: '0px',
            lineHeight: '34px'
          }}>
            <button
              className={cx({
                'btn-blue':this.props.spanTime <= moment.duration(1, 'months').valueOf(),
                'btn-sm':true,
                'btn-hollow':this.state.endTime !== moment().startOf('day').subtract(1, 'months').valueOf(),
                'btn-disabled':this.props.spanTime > moment.duration(1, 'months').valueOf()
              })}
              disabled={this.props.spanTime > moment.duration(1, 'months').valueOf()}
              onClick={this.selectDay.bind(this, false)}>
              上月同期
            </button>
            <button
              className={cx({
                'btn-blue':this.props.spanTime <= moment.duration(1, 'weeks').valueOf(),
                'btn-sm':true,
                'btn-hollow':this.state.endTime !== moment().startOf('day').subtract(1, 'weeks').valueOf(),
                'btn-disabled':this.props.spanTime > moment.duration(1, 'weeks').valueOf()
              })}
              disabled={this.props.spanTime > moment.duration(1, 'weeks').valueOf()}
              onClick={this.selectDay.bind(this, true)}>
              上周同期
            </button>
          </span>
          <button onClick={this.applyHandler} className="btn-green" type="button">确定</button>
        </div>
      </div>
    )
  }

  render() {
    let currentStyle = _.extend({float:'left'}, this.props.style);
    return (
      <div className="dropdown time-slider" style={currentStyle} ref="root">
        <strong onClick={this.toggle}>
          <i className="iconfont icon-clock"></i>
          {this.state.displayText}
          <i className="iconfont icon-btn-arrow">&#xe619;</i>
        </strong>
        {
          this.state.isOpen ? this.renderBody() : null
        }
      </div>
    )
  }
}

DateComparerPicker.defaultProps = {
  spanTime: moment.duration(1, 'days').valueOf(),
  id:null,
  endTime:null,
  displayText:null,
  style: {}
}
